/*
 *  deserialize.cc
 *  wonderland-project
 *
 *  Created by Ben Nolan on 15/10/08.
 *  Copyright 2008 Nolan Consulting Limited. All rights reserved.
 *
 */

#include "deserialize.h"
#include <Ogre.h>
#include "tinyxml/tinyxml.h"
#include "region.h"

namespace Wonderland{

Ogre::Entity* entityfromXml(TiXmlElement *el, Region *region){
  region->getSceneManager()->destroyEntity(el->Attribute("id"));

  return region->getSceneManager()->createEntity(el->Attribute("id"), el->Attribute("src"));
}

void deserializeFromXml(TiXmlElement *el, Region *region){
	Ogre::SceneNode *node;
	Ogre::Vector3 v;
	Ogre::Quaternion q;
	
	node = 0;
	
	std::cout << "Processing node " << el->Attribute("id") << "..." << std::endl;

	if(el->Value() == (std::string) "node"){
		// Does the node exist?
		if (region->getSceneManager()->hasSceneNode(el->Attribute("id"))){
			node = region->getSceneManager()->getSceneNode(el->Attribute("id"));
		}else{
			// Add the node ja?
			node = region->createNode(el->Attribute("id"));
		}
	}

	// Set position, rotation, scale
	
  TiXmlElement *needle = el->FirstChildElement(); 
  
  while(needle){
    if((node) && (needle->Value() == (std::string) "translate")){
  		std::cout << "  translate: " << el->FirstChildElement("translate")->GetText() << std::endl;
      sscanf(needle->GetText(), "%f %f %f",	&v.x, &v.y, &v.z);
      node->setPosition(v);
    }

    if((node) && (needle->Value() == (std::string) "scale")){
  		std::cout << "  scale: " << el->FirstChildElement("scale")->GetText() << std::endl;
      sscanf(needle->GetText(), "%f %f %f",	&v.x, &v.y, &v.z);
      node->setScale(v);
    }

    if((node) && (needle->Value() == (std::string) "rotate")){
  		std::cout << "  rotate: " << el->FirstChildElement("rotate")->GetText() << std::endl;
      sscanf(needle->GetText(), "%f %f %f %f", &q.w, &q.x, &q.y, &q.z);
      node->setOrientation(q);
    }
    
//    if((node) && (needle->Value() == (std::string) "entity")){
//      // todo: fix the OMGBSHAXLOL
//      node->detachObject((unsigned short) 0);
//      node->attachObject(entityfromXml(needle, region));
//    }

    if(needle->Value() == (std::string) "node"){
      deserializeFromXml(needle, region);
    }
    
    needle = needle->NextSiblingElement();
  }
}

void Deserialize(std::string xml, Region *region){
	TiXmlDocument doc;
	
  if(doc.Parse(xml.c_str())){
    deserializeFromXml(doc.FirstChildElement(), region);
  }
}


}